import { CustomPage } from '/engine/index';
import {
  getUserInfo,
  updateUserInfo as fetchUpdateUserInfo,
  uploadAvatar,
  getSmsCode,
} from '../../services/user';
import { desensitize, calculateBMI, parseIDCard } from '../../utils/index';

CustomPage({
  data: {
    avatar: '',
    nickName: '',
    phonenumber: '',
    sex: '',
    birthday: '',
    height: '',
    weight: '',
    bmi: '',
    userName: '',
    idCardNumber: '',
    validityCode: '',
    isValidityCode: false,
    disableCode: false,
    userInfo: {},
    countdown: 60,
    visibleCardId: false,
    visibleNickName: false,
    visiblePhoneNum: false,
    visibleSex: false,
    visibleHeight: false,
    visibleWeight: false,
    // 编辑时使用的临时变量
    nickNameInput: '',
    sexInput: '',
    birthdayInput: '',
    heightInput: '',
    weightInput: '',
    userNameInput: '',
    idCardNumberInput: '',
    phoneInput: '',
  },
  async onLoad() {
    const userInfo = await getUserInfo();
    this.setData({
      userInfo: userInfo?.data,
      avatar: userInfo?.data?.avatar,
      nickName: userInfo?.data?.nickName,
      phonenumber: desensitize('phone', userInfo?.data?.phonenumber),
      sex: userInfo?.data?.sex,
      birthday: userInfo?.data?.birthday,
      height: userInfo?.data?.height,
      weight: userInfo?.data?.weight,
      bmi: userInfo?.data?.bmi,
      userName: desensitize('name', userInfo?.data?.patientName),
      idCardNumber: desensitize('idCard', userInfo?.data?.idCardNumber),
    });
  },
  onClickBack() {
    wx.navigateBack();
  },
  async updateUserInfo(prams) {
    await fetchUpdateUserInfo({
      ...this.data.userInfo,
      ...prams,
    });
  },
  chooseAvatar() {
    wx.showActionSheet({
      itemList: ['拍照', '从相册选择'],
    })
      .then(res => {
        const sourceType = res.tapIndex === 0 ? ['camera'] : ['album'];

        // 打开图片选择器
        wx.chooseMedia({
          count: 1,
          mediaType: ['image'],
          sourceType: sourceType,
          camera: 'front', // 默认使用前置摄像头
        })
          .then(async result => {
            const tempFilePath = result.tempFiles[0].tempFilePath;
            // 设置本地预览
            this.setData({
              avatar: tempFilePath,
            });
            const resp = await uploadAvatar(tempFilePath);
            this.setData({ avatar: resp.imgUrl });
            await this.updateUserInfo({ avatar: resp.imgUrl });
          })
          .catch(err => {
            wx.showToast({ title: '取消选择', icon: 'none' });
          });
      })
      .catch(err => {
        wx.showToast({ title: '操作失败', icon: 'none' });
      });
  },
  onClickEditCardId() {
    this.setData({ visibleCardId: true });
  },
  onCancelCardId() {
    this.setData({ visibleCardId: false });
  },
  onConfirmCardId() {
    const { userNameInput, idCardNumberInput } = this.data;
    if (!userNameInput || !idCardNumberInput) {
      wx.showToast({ title: '请输入有效信息', icon: 'none' });
      return;
    }
    const { valid } = parseIDCard(idCardNumberInput);
    if (!valid) {
      wx.showToast({ title: '请输入有效身份证信息', icon: 'none' });
      return;
    }
    this.setData({
      visibleCardId: false,
      userName: desensitize('name', userNameInput),
      idCardNumber: desensitize('idCard', idCardNumberInput),
    });
    this.updateUserInfo({
      patientName: userNameInput,
      idCardNumber: idCardNumberInput,
    });
  },
  onInputUserName(e) {
    this.setData({ userNameInput: e.detail.value });
  },
  onInputIdCardNumber(e) {
    this.setData({ idCardNumberInput: e.detail.value });
  },
  onClickEditNickName() {
    this.setData({
      visibleNickName: true,
      nickNameInput: this.data.nickName,
    });
  },
  onInputNickName(e) {
    this.setData({ nickNameInput: e.detail.value });
  },
  onCancelNickName() {
    this.setData({ visibleNickName: false });
  },
  onConfirmNickName() {
    const newNickName = this.data.nickNameInput.trim();
    if (!newNickName) {
      wx.showToast({ title: '昵称不能为空', icon: 'none' });
      return;
    }
    this.setData({
      nickName: newNickName,
      visibleNickName: false,
    });
    this.updateUserInfo({ nickName: newNickName });
  },
  onClickEditSex() {
    this.setData({ visibleSex: true });
  },
  onChangeSex(e) {
    const sexMap = ['0', '1'];
    this.setData({ sexInput: sexMap[e.detail.value] });
  },
  onCancelSex() {
    this.setData({ visibleSex: false });
  },
  onConfirmSex() {
    const newSex = this.data.sexInput;
    this.setData({
      sex: newSex,
      visibleSex: false,
    });
    this.updateUserInfo({ sex: newSex });
  },
  onChangeBirthday(e) {
    const date = e.detail.value;
    const year = parseInt(date.slice(0, 4));
    const month = parseInt(date.slice(5, 7));
    const day = parseInt(date.slice(8, 10));
    const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    this.setData({
      birthday: formattedDate,
    });
    this.updateUserInfo({ birthday: formattedDate });
  },
  onClickEditHeight() {
    this.setData({
      visibleHeight: true,
      heightInput: this.data.height,
    });
  },
  onInputHeight(e) {
    this.setData({ heightInput: e.detail.value });
  },
  onCancelHeight() {
    this.setData({ visibleHeight: false });
  },
  onConfirmHeight() {
    const newHeight = this.data.heightInput.trim();
    if (!newHeight || isNaN(newHeight)) {
      wx.showToast({ title: '请输入有效身高', icon: 'none' });
      return;
    }
    const { bmi } = calculateBMI(Number(newHeight), Number(this.data.weight));
    this.setData({
      height: newHeight,
      bmi,
      visibleHeight: false,
    });
    this.updateUserInfo({ height: newHeight, bmi });
  },
  onClickEditWeight() {
    this.setData({
      visibleWeight: true,
      weightInput: this.data.weight,
    });
  },
  onInputWeight(e) {
    this.setData({ weightInput: e.detail.value });
  },
  onCancelWeight() {
    this.setData({ visibleWeight: false });
  },
  onConfirmWeight() {
    const newWeight = this.data.weightInput.trim();
    if (!newWeight || isNaN(newWeight)) {
      wx.showToast({ title: '请输入有效体重', icon: 'none' });
      return;
    }
    const { bmi } = calculateBMI(Number(this.data.height), Number(newWeight));
    this.setData({
      bmi,
      weight: newWeight,
      visibleWeight: false,
    });

    this.updateUserInfo({ weight: newWeight, bmi });
  },
  onClickEditPhone() {
    this.setData({ visiblePhoneNum: true });
  },
  onInputPhone(e) {
    this.setData({ phoneInput: e.detail.value });
  },
  onInputIdCode(e) {
    this.setData({ validityCode: e.detail.value });
  },
  onCancelPhone() {
    this.setData({ visiblePhoneNum: false });
  },
  onConfirmPhone() {
    const { phoneInput, validityCode, isValidityCode } = this.data;
    if (!phoneInput || !validityCode) {
      wx.showToast({
        title: '请检查输入的手机号和验证码不能为空',
        icon: 'none',
      });
      return;
    }
    if (!isValidityCode) {
      wx.showToast({ title: '请验证手机成功后再试', icon: 'none' });
      return;
    }
    // TODO
    this.setData({
      visiblePhoneNum: false,
      phonenumber: desensitize('phone', phoneInput),
    });
    this.updateUserInfo({
      phonenumber: phoneInput,
      phoneAuthCode: validityCode,
    });
  },
  async onSendCode() {
    const { phoneInput } = this.data;
    if (this.data.disableCode) {
      return;
    }
    if (phoneInput.length < 11) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' });
      return;
    }
    this.setData({ disableCode: true, isValidityCode: true });
    await getSmsCode(phoneInput);

    const timer = setInterval(() => {
      let { countdown } = this.data;
      countdown--;

      if (countdown <= 0) {
        clearInterval(timer);
        this.setData({
          disableCode: false,
          countdown: 60,
        });
      } else {
        this.setData({ countdown });
      }
    }, 1000);
  },
});
